<?php

namespace app\adminapi\controller\v2;

use app\adminapi\controller\AuthController;
use app\model\admin\TrainTypeModel;
use app\model\plan\PlanCourse;
use app\model\system\admin\SystemAdmin;
use think\exception\ValidateException;
use think\Request;

class Admin extends AuthController
{
    public function list(Request $request)
    {
        $page = input('page', 1);
        $limit = input('size', 10);

        $where = [];
        $where[] = ['id', '<>', 2];
        $account = $request->param('account', '');
        if ($account) {
            $where[] = ['account', 'like', '%' . $account . '%'];
        }
        $real_name = $request->param('real_name', '');
        if ($real_name) {
            $where[] = ['real_name', 'like', '%' . $real_name . '%'];
        }

        $data = SystemAdmin::order('id', 'desc')
            ->where($where)
            ->where('level', 1)
            ->where('is_del', 0)
            ->paginate($limit)
            ->each(function ($item) {
            });

        return app('json')->success([
            'total' => $data->total(),
            'list' => $data->items(),
        ]);
    }

    public function info(Request $request)
    {
        $id = input('id', '');
        if ($id) {
            $data = SystemAdmin::where('id', $id)
                ->find();
            unset($data->pwd);
        } else {
            $data = null;
        }
        return app('json')->success([
            'data' => $data,
        ]);
    }

    public function save(Request $request)
    {
        $data = $request->only([
            'account', 'real_name', 'pwd' => '',
        ]);
        $id = input('id', '');
        try {
            validate([
                'account|账号' => 'require|max:32',
                'real_name|姓名' => 'require|max:16',
            ])->check($data);
        } catch (ValidateException $exception) {
            return app('json')->fail($exception->getMessage());
        }
        if ($data['pwd']) {
            $data['pwd'] = password_hash($data['pwd'], PASSWORD_DEFAULT);
        }
        if (!$id) {
            $data['roles'] = 1;
            $data['add_time'] = time();
            $exists = SystemAdmin::where('account', $data['account'])->find();
            if ($exists) {
                return app('json')->fail('账号已存在');
            }
            SystemAdmin::create($data);
        } else {
            $exists = SystemAdmin::where('account', $data['account'])
                ->where('id', '<>', $id)
                ->find();
            if ($exists) {
                return app('json')->fail('账号已存在');
            }
            SystemAdmin::update($data, ['id' => $id]);
        }
        return app('json')->success();
    }

    public function delete(Request $request)
    {
        $id = input('id', '');
        SystemAdmin::update([
            'id' => $id,
            'is_del' => 1,
            'status' => 0,
        ]);
        return app('json')->success();
    }
}